package device

import (
	"device-admin/config/mysql"
	"device-admin/internal/define"
	"device-admin/internal/models"
	"time"
)

// DeviceTypes 设备类型
func DeviceTypes(online int, merchantID string) interface{} {
	type deviceTypeT struct {
		ID        int    `json:"id"`
		Name      string `json:"name"`
		DeviceNum int    `json:"device_num,omitempty"`
	}
	var deviceTypes []deviceTypeT
	// 如果没有在线条件，展示全部
	if online == -1 {
		for k, v := range define.DeviceType {
			deviceTypes = append(deviceTypes, deviceTypeT{
				ID:   int(k),
				Name: string(v),
			})
		}
		return deviceTypes
	} else {
		var list []struct {
			DeviceNum  int `gorm:"column:device_num"`
			DeviceType int `gorm:"column:device_type"`
		}
		// 数据库连接
		tx := mysql.NewDB().Model(&models.Device{})
		// 在线条件
		if online == 0 {
			tx.Where("latest_active_time < ?", time.Now().Unix()-60)
		} else if online == 1 {
			tx.Where("latest_active_time > ?", time.Now().Unix()-60)
		}
		tx.Where("merchant_id = ?", merchantID).
			Select(
				"sum(*) as device_num",
				"device_type",
			).
			Group("device_type").
			Find(&list)
		for _, record := range list {
			deviceTypes = append(deviceTypes, deviceTypeT{
				ID:        record.DeviceType,
				Name:      define.DeviceType[record.DeviceType],
				DeviceNum: record.DeviceNum,
			})
		}
		return deviceTypes
	}
}
